from typing import Dict, Any, Optional, Tuple
from .database_tool import DatabaseTool
from .nlp_tool import NLPTool
import uuid
from decimal import Decimal

class InventoryTool:
    def __init__(self, db_tool: DatabaseTool, nlp_tool: NLPTool):
        self.db_tool = db_tool
        self.nlp_tool = nlp_tool
        self.current_transaction = None

    def process_purchase(self, query: str) -> Dict[str, Any]:
        """处理购买请求"""
        try:
            # 解析购买意图
            intent = self.nlp_tool.parse_purchase_intent(query)
            if not intent.get('success'):
                return {
                    "success": False,
                    "message": "无法理解您的购买请求，请重新描述",
                    "data": None
                }

            # 存储成功处理的商品
            success_products = []
            total_amount = Decimal('0.0')
            
            # 检查所有商品是否可用
            for item in intent['items']:
                # 获取商品信息
                product = self.db_tool.get_product_by_name(item['product_name'])
                if not product:
                    return {
                        "success": False,
                        "message": f"未找到商品: {item['product_name']}",
                        "data": None
                    }

                # 检查库存
                if product['stock'] < item['quantity']:
                    return {
                        "success": False,
                        "message": f"{product['name']}库存不足，当前库存: {product['stock']}{item['unit']}",
                        "data": None
                    }

                # 计算商品总价
                item_total = Decimal(str(product['price'])) * Decimal(str(item['quantity']))
                total_amount += item_total

                # 添加到成功处理列表
                success_products.append({
                    "product_id": product['id'],
                    "product_name": product['name'],
                    "quantity": item['quantity'],
                    "unit": item['unit'],
                    "price": float(product['price']),
                    "amount": float(item_total)
                })

            # 如果没有指定支付方式，返回友好提示
            if not intent.get('payment_method'):
                # 构建响应消息
                message = "您需要说明支付方式。\n\n"
                message += "正确的购买格式是：用[支付方式]购买[数量][单位][商品名]。\n"
                message += "例如：用现金购买10斤苹果和5斤香蕉\n"
                message += "支持的支付方式：现金、信用卡、移动支付\n\n"
                
                if success_products:
                    message += "您的购物清单：\n"
                    for product in success_products:
                        message += f"- {product['quantity']}{product['unit']}{product['product_name']}，单价：{product['price']}元\n"
                    message += f"\n总金额：{float(total_amount)}元\n"
                    message += "\n请完整描述您的购买意图，包含支付方式。"
                
                return {
                    "success": False,
                    "message": message,
                    "data": None
                }

            # 保存当前交易信息
            self.current_transaction = {
                "products": success_products,
                "total_amount": float(total_amount)
            }

            # 如果指定了支付方式，处理支付和库存更新
            try:
                # 先处理支付
                valid, payment_method = self.nlp_tool.parse_payment_method(query)
                if not valid:
                    return {
                        "success": False,
                        "message": "不支持的支付方式，请选择：现金/信用卡/移动支付",
                        "data": None
                    }

                # 更新库存并创建销售记录
                for product in success_products:
                    # 再次检查库存（以防在等待支付过程中库存发生变化）
                    current_stock = self.db_tool.check_stock(product["product_id"])
                    if current_stock['stock'] < product['quantity']:
                        return {
                            "success": False,
                            "message": f"{product['product_name']}库存不足，当前库存: {current_stock['stock']}{product['unit']}",
                            "data": None
                        }
                    
                    # 更新库存
                    self.db_tool.update_stock(
                        product["product_id"],
                        int(product["quantity"]),
                        "Out",
                        "收银员"
                    )

                    # 处理支付
                    success, amount = self.db_tool.process_payment(
                        product["product_id"],
                        int(product["quantity"]),
                        payment_method
                    )
                    
                    if not success:
                        raise Exception(f"商品 {product['product_name']} 支付处理失败")

                # 生成支付成功响应
                response = self.nlp_tool.generate_response("purchase_success", {
                    "products": success_products,
                    "total_amount": float(total_amount),
                    "payment_method": payment_method
                })

                # 清除当前交易
                transaction_data = self.current_transaction
                self.current_transaction = None

                return {
                    "success": True,
                    "message": response,
                    "data": transaction_data
                }

            except Exception as e:
                error_msg = str(e)
                print(f"处理支付和库存更新时出错: {error_msg}")
                return {
                    "success": False,
                    "message": f"处理失败: {error_msg}",
                    "data": None
                }

        except Exception as e:
            print(f"处理购买请求时出错: {str(e)}")
            return {
                "success": False,
                "message": f"处理请求时出错: {str(e)}",
                "data": None
            }

    def process_payment(self, query: str) -> Dict[str, Any]:
        """处理支付请求"""
        try:
            if not self.current_transaction:
                return {
                    "success": False,
                    "message": "没有待支付的订单",
                    "data": None
                }

            # 解析支付方式
            valid, payment_method = self.nlp_tool.parse_payment_method(query)
            if not valid:
                return {
                    "success": False,
                    "message": "不支持的支付方式，请选择：现金/信用卡/移动支付",
                    "data": None
                }

            try:
                # 处理每个商品的支付
                for product in self.current_transaction["products"]:
                    success, amount = self.db_tool.process_payment(
                        product["product_id"],
                        int(product["quantity"]),
                        payment_method
                    )
                    
                    if not success:
                        raise Exception(f"商品 {product['product_name']} 支付处理失败")

                # 生成支付成功响应
                response = self.nlp_tool.generate_response("purchase_success", {
                    "products": self.current_transaction["products"],
                    "total_amount": self.current_transaction["total_amount"],
                    "payment_method": payment_method
                })

                # 清除当前交易
                transaction_data = self.current_transaction
                self.current_transaction = None

                return {
                    "success": True,
                    "message": response,
                    "data": transaction_data
                }

            except Exception as e:
                error_msg = str(e)
                print(f"支付处理出错: {error_msg}")
                return {
                    "success": False,
                    "message": f"支付失败: {error_msg}",
                    "data": None
                }

        except Exception as e:
            print(f"处理支付请求时出错: {str(e)}")
            return {
                "success": False,
                "message": "处理支付请求时出现错误",
                "data": None
            }

    def process_restock(self, query: str) -> Dict[str, Any]:
        """处理补货请求"""
        try:
            # 解析补货意图
            intent = self.nlp_tool.parse_restock_intent(query)
            if intent["type"] != "restock":
                return {
                    "success": False,
                    "message": "无法理解您的补货请求",
                    "data": None
                }

            # 查找商品
            product = self.db_tool.get_product_by_name(intent["product_name"])
            if not product:
                return {
                    "success": False,
                    "message": self.nlp_tool.generate_response("restock_failed", {
                        "product_name": intent["product_name"],
                        "quantity": intent["quantity"],
                        "unit": intent["unit"],
                        "reason": "商品不存在"
                    }),
                    "data": None
                }

            # 检查单位是否匹配
            category = product["category_name"]
            expected_unit = self.nlp_tool.category_units.get(category, "件")
            if intent["unit"] != expected_unit:
                return {
                    "success": False,
                    "message": self.nlp_tool.generate_response("restock_failed", {
                        "product_name": product["name"],
                        "quantity": intent["quantity"],
                        "unit": intent["unit"],
                        "reason": f"该商品的单位应为{expected_unit}"
                    }),
                    "data": None
                }

            # 更新库存
            try:
                self.db_tool.update_stock(
                    product["id"],
                    intent["quantity"],
                    "In",
                    "补货员"
                )

                # 获取更新后的库存信息
                updated_product = self.db_tool.get_product_by_id(product["id"])
                
                return {
                    "success": True,
                    "message": self.nlp_tool.generate_response("restock_success", {
                        "product_name": product["name"],
                        "quantity": intent["quantity"],
                        "unit": intent["unit"],
                        "current_stock": updated_product["stock"]
                    }),
                    "data": updated_product
                }

            except Exception as e:
                return {
                    "success": False,
                    "message": self.nlp_tool.generate_response("restock_failed", {
                        "product_name": product["name"],
                        "quantity": intent["quantity"],
                        "unit": intent["unit"],
                        "reason": str(e)
                    }),
                    "data": None
                }

        except Exception as e:
            print(f"处理补货请求时出错: {str(e)}")
            return {
                "success": False,
                "message": "处理补货请求时出现错误",
                "data": None
            }

    def get_low_stock_alerts(self, threshold: int = 10) -> Dict[str, Any]:
        """获取库存预警"""
        try:
            low_stock_products = self.db_tool.get_low_stock_products(threshold)
            if not low_stock_products:
                return {
                    "success": True,
                    "message": "所有商品库存充足",
                    "data": []
                }

            # 构建预警信息
            alerts = []
            for product in low_stock_products:
                category = product["category_name"]
                unit = self.nlp_tool.category_units.get(category, "件")
                alerts.append(f"{product['name']}: 当前库存{product['stock']}{unit}")

            return {
                "success": True,
                "message": f"发现{len(alerts)}个库存不足的商品：\n" + "\n".join(alerts),
                "data": low_stock_products
            }

        except Exception as e:
            print(f"获取库存预警时出错: {str(e)}")
            return {
                "success": False,
                "message": "获取库存预警时出现错误",
                "data": None
            } 